package com.gexiaobao.pigeon.ui.auction

import android.annotation.SuppressLint
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.recyclerview.widget.GridLayoutManager
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseActivity
import com.gexiaobao.pigeon.app.eventViewModel
import com.gexiaobao.pigeon.app.ext.RxTextTool
import com.gexiaobao.pigeon.app.ext.init
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.StatusBarUtil
import com.gexiaobao.pigeon.app.util.Util
import com.gexiaobao.pigeon.app.weight.recycleview.SpaceItemDecoration
import com.gexiaobao.pigeon.databinding.ActivityMarginPaymentBinding
import com.gexiaobao.pigeon.ui.adapter.AdapterRechargeMoney
import com.gexiaobao.pigeon.ui.dialog.RxDialogDefault
import com.gexiaobao.pigeon.viewmodel.AuctionViewModel
import com.google.gson.Gson
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import java.text.DecimalFormat

/**
 * @Author      : hxw
 * @Date        : 2024/12/4 17:42
 * @Describe    : 退还保证金
 */
class ActivityReturnMargin : BaseActivity<AuctionViewModel, ActivityMarginPaymentBinding>() {

    private var mRemainMoney: Double = 0.0
    private val adapter: AdapterRechargeMoney by lazy { AdapterRechargeMoney(arrayListOf()) }

    @SuppressLint("SetTextI18n")
    override fun initView(savedInstanceState: Bundle?) {
        StatusBarUtil.setTranslucentForImageView(this, 0, null)
        mDatabind.tvMarginPayment.text = "退还保证金"
        mDatabind.tvMarginPaymentEn.text = "Return deposit"
        mDatabind.tvMarginAmount.text = "退还金额"
        mDatabind.etMarginPaymentMoney.hint = "输入保证金退还金额"
        mDatabind.tvMarginPaymentAgreement.isVisible = false
        mDatabind.tvMarginPaymentTopUp.text = "退还"
        mDatabind.tvReturnMargin.isVisible = false
        mDatabind.tvMastRead.isVisible = false
        mViewModel.getTotalFreezeMoney()
        mDatabind.recyclerView.init(GridLayoutManager(this, 3), adapter)
            .addItemDecoration(SpaceItemDecoration(Util.dp2px(this, 10f), Util.dp2px(this, 30f)))

        initAdapterData()
        setMarginBalance()

        mDatabind.swipeRefreshLayout.init {
            mViewModel.getTotalFreezeMoney()
        }
        mDatabind.etMarginPaymentMoney.addTextChangedListener(object : TextWatcher {
            private var isUpdating = false
            override fun beforeTextChanged(charSequence: CharSequence?, start: Int, before: Int, count: Int) {}
            override fun onTextChanged(charSequence: CharSequence?, start: Int, before: Int, count: Int) {}
            override fun afterTextChanged(s: Editable?) {
                if (!isUpdating) {
                    isUpdating = true
                    var text = s.toString()
                    // 检查是否包含小数点
                    val containsDot = text.contains(".")
                    // 如果包含小数点，则检查第一个小数点后的位数
                    if (containsDot) {
                        val parts = text.split("\\.".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
                        if (parts.size > 1 && parts[1].length > 2) {
                            // 超过两位数，截取到小数点后两位
                            text = parts[0] + "." + parts[1].substring(0, 2)
                        }
                    }
                    // 补充小数点前的0，如果第一个字符是小数点
                    if (text.startsWith(".") && !text.startsWith("0.")) {
                        text = "0$text"
                    }

                    // 更新EditText的内容
                    mDatabind.etMarginPaymentMoney.removeTextChangedListener(this)
                    mDatabind.etMarginPaymentMoney.setText(text)
                    mDatabind.etMarginPaymentMoney.getText()?.let { mDatabind.etMarginPaymentMoney.setSelection(it.length) }
                    mDatabind.etMarginPaymentMoney.addTextChangedListener(this)
                    isUpdating = false
                }
            }
        })
    }

    override fun createObserver() {
        super.createObserver()
        /** 获取保证金信息 */
        mViewModel.freezeMoneyResult.observe(this) {
            if (mDatabind.swipeRefreshLayout.isRefreshing) {
                mDatabind.swipeRefreshLayout.isRefreshing = false
            }
            mRemainMoney = it.remainMoney
            setMarginBalance()
        }
        /** 退还保证金 */
        mViewModel.returnMarginResult.observe(this) {
            mViewModel.getTotalFreezeMoney()
            eventViewModel.toRefreshData.value = true
        }
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(mDatabind.ivMarginPaymentBack, mDatabind.tvAllReturnMargin, mDatabind.tvMarginPaymentTopUp) {
            when (it) {
                mDatabind.tvMarginPaymentTopUp -> showReturnDialog()
                mDatabind.tvAllReturnMargin -> returnMargin()
                mDatabind.ivMarginPaymentBack -> finish()
            }
        }
    }

    private fun returnMargin() {
        if (mRemainMoney == 0.0) {
            RxToast.warning("暂无保证金")
            return
        }
        mDatabind.etMarginPaymentMoney.setText(mRemainMoney.toString())
        mDatabind.etMarginPaymentMoney.setSelection(mDatabind.etMarginPaymentMoney.text.toString().length)
    }

    private fun setMarginBalance() {
        val mRemainMoney = if (mRemainMoney >= 1000) {
            formatAmount(mRemainMoney)
        } else {
            mRemainMoney
        }
        RxTextTool.getBuilder("当前保证金余额: ")
            .append("￥ $mRemainMoney").setAppearance(56).setBold()
            .setTextColor(ContextCompat.getColor(this, R.color.color_fe4542))
            .into(mDatabind.tvMarginBalance)
    }

    private fun formatAmount(amount: Double): String {
        val formatter = DecimalFormat("#,###.00")
        return formatter.format(amount)
    }

    private fun showReturnDialog() {
        val dialog = RxDialogDefault(this)
        dialog.setTitle("温馨提示")
        dialog.setContent("退还后的保证金可在个人中心中查看,\n确定退还吗?")
        dialog.setSureListener {
            dialog.dismiss()
            returnMarginBalance()
        }
        dialog.setFullScreenWidth()
        dialog.show()
    }

    private fun returnMarginBalance() {
        val money = mDatabind.etMarginPaymentMoney.text.toString()
        if (money.isEmpty()) {
            RxToast.warning("请输入要退还的金额")
            return
        }
        if (mDatabind.etMarginPaymentMoney.text?.endsWith(".") == true){
            RxToast.warning("请输入正确的金额")
            return
        }
        val map = mapOf("returnMoney" to money.toDouble())
        val body: RequestBody = Gson().toJson(map).toRequestBody("application/json".toMediaTypeOrNull())
        showLoading(getString(R.string.loading))
        mViewModel.returnBond(body)
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun initAdapterData() {
        val mList = listOf("￥200", "￥500", "￥800", "￥1200", "￥1500", "￥1800")
        adapter.setList(mList)
        adapter.notifyDataSetChanged()

        adapter.setOnItemClickListener { _, _, position ->
            mDatabind.etMarginPaymentMoney.setText(mList[position].substring(1, mList[position].length))
            mDatabind.etMarginPaymentMoney.setSelection(mDatabind.etMarginPaymentMoney.text.toString().length)
        }
    }
}